package com.gt.aep.base.config;

import com.gt.aep.base.entity.systemManage.SysRole;
import com.gt.aep.base.entity.systemManage.SysUser;
import com.gt.aep.base.service.systemManage.SysRoleService;
import com.gt.aep.base.service.systemManage.SysRoleUserService;
import com.gt.aep.base.service.systemManage.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShrioRealm  extends AuthorizingRealm{
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysRoleUserService sysRoleUserService;


    //当涉及角色权限验证时候调用doGetAuthorizationInfo
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser u=(SysUser) SecurityUtils.getSubject().getSession().getAttribute("userKey");
        List<SysRole> roleList=sysRoleUserService.getRoleListByUid(u.getId());
        SimpleAuthorizationInfo szf=new SimpleAuthorizationInfo();
        for (SysRole role : roleList) {
            szf.addRole(role.getName());
            System.out.println(role.getName());
        }
        return szf;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //取出token 的用户名  authenticationToken;
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
        SysUser user=sysUserService.getUserByUserName(userName);

        if (user !=null ){
            //把用户信息存储到subejct的session里
            SecurityUtils.getSubject().getSession().setAttribute("userKey",user);
            //返回该方法的【简单】对象AuthenticationInfo，里面要有三个参数：账号名 数据库里的密码    getName的方法（Realm的名字" " 未定义，允许配置多个Realm链接多个数据库  ）
            SimpleAuthenticationInfo sif=new SimpleAuthenticationInfo(
                    userName,
                    user.getPassword(),
                    getName()
            ) ;
            return  sif;

        }else{
            throw new AuthenticationException("用户不存在");
        }
    }
}
